<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace App\Views\Lib;

use Sun\Sun;
use Sun\Html;
use App\Models;
use App\Models\DB;
use Sun\Utils;


class Reader extends Main {
    public function __construct() {
        parent::__construct();
        $this->data_scene = 'ReaderList';
    }


    public function AltScene() {
        if (empty($this->cond)) {
            $user = new Models\User();
            $profile = $user->UserInfo($this->data['user_id']);
            $this->data = array_merge($this->data, $profile);
        }
        $this->IncludeScene("AltBody");
    }

    public function ReaderListPageScene() {
        $users = new Models\User();

        $field = @$this->data['SearchField'];
        $val = @$this->data['SearchValue'];
        $p = $this->data['Page'];
        $deb = $this->data['debetor'];

        $num_rows = Sun::conf('iface/usr_rows');
        $offset = $num_rows * ($p - 1);

        $cond = empty($val) ? 'true' : "lower({$field}::VARCHAR) LIKE lower({$users->db->quote($val)})";

        if ($deb == 'true') {
            $res = $users->DebetorList($offset, $num_rows, $cond);
            $num_pages = ceil($users->DebetorCount($cond) / $num_rows);
        } else {

            $res = $users->ReaderList($offset, $num_rows, $cond);
            $num_pages = ceil($users->ReaderCount($cond) / $num_rows);

        }

        $table = new Html\QueryTable($res->fetchAll(DB::FETCH_ASSOC),
                array('Ид', 'Логин', 'ФИО', 'Дата регистрации', 'Дата окончания'));

        $table->SetAttribute('class', $table->Attribute('class').' UserList');
        $table->id = 'ListUserTable';

        $rows = $table->First()->Childs();
        $rows[0]->AddData()->Added()->SetAttribute('class', 'AlignCenter');

        for ($i = 1; $i < count($rows); ++$i) {
            $id = $rows[$i]->First()->First()->value;
            $rows[$i]->SetAttribute("data-id", $id)
                ->AddData()->Added()->SetAttribute('class', 'AlignCenter')
                    ->Add(new Html\A(array('href' => '?')))
                    ->Added()->Add(new Html\Img(array(
                        'style' => 'border: none',
                        'src' => 'pub/media/images/user_info_16.png',
                        'alt' => 'Изменить'
                     )));
        }

        ////////////////// javascript //////////////////////
        $src = Utils::LoadFileToString(dirname(__FILE__)."/Reader/ReaderList.js");
        $script = new Html\Script($src);
        ////////////////////////////////////////////////////

        $div = new Html\Div();
        $div->add($table);
        $div->Add($script);

        $query_res = "{ content: {$div->ToJSON()}, num_pages: {$num_pages} }";

        echo $query_res;
    }

    public function OrderListScene() {
        echo $this->Orders()->ToJSON();
    }

    public function IssueListScene() {
        echo $this->Issues()->ToJSON();
    }


    public function UserListSwitch() {
        $page_switch = new Html\PageSwitch("ReaderList");
        return $page_switch->ToHtml();
    }

    public function Orders() {
        $user = new Models\User();
        $sess = new Models\Session();
        $edit = new Models\Edition();

        $orders = $user->GetOrders($this->data['user_id']);

        $rows = array();
        for ($i = 0; $i < count($orders); ++$i) {
            $rows[] = array($i + 1, $edit->GetEditCatalogBrief($orders[$i]['edit_id']));
        }

        $table = new Html\QueryTable($rows, array("№", "Описание"));
        $table->id = "ReaderOrderTable";
        $table->SetAttribute('class', $table->Attribute('class').' EditionList');

        $rows = $table->First()->Childs();
        $rows[0]->First()->SetAttribute("class", "ControlCell");
        $rows[0]->AddData()->Added()->SetAttribute("class", "ControlCell");
        $rows[0]->AddData()->Added()->SetAttribute("class", "ControlCell");

        for ($i = 1; $i < count($rows); ++$i) {
            $order_id = $i ? $orders[$i - 1]['order_id'] : "";
            $edit_id = $i ? $orders[$i - 1]['edit_id'] : "";

            $rows[$i]->First()->SetAttribute("style", "text-align: center");

            $rows[$i]->AddData()->Added()->SetAttribute("style", "text-align: center")
                ->Add(new Html\A(array('href' => '?',
                    'data-order' => $order_id, 'data-edit' => $edit_id)))
                ->Added()->Add(new Html\Img(array(
                    'src' => "pub/media/images/tick_16.png",
                    'class' => "NoneBorder",
                    'alt' => 'Выдать')));

            $rows[$i]->AddData()->Added()->SetAttribute("style", "text-align: center")
                ->Add(new Html\A(array('href' => '?',
                    'data-order' => $order_id, 'data-edit' => $edit_id)))->Added()
                ->Add(new Html\Img(array(
                    'src' => "pub/media/images/clear_16.png",
                    'class' => "NoneBorder",
                    'alt' => 'Удалить')));
        }

        ////////////////// javascript //////////////////////
        $src = Utils::LoadFileToString(dirname(__FILE__)."/Reader/Order.js");
        $script = new Html\Script($src);
        ////////////////////////////////////////////////////

        $div = new Html\Div();
        $div->add($table);
        $div->Add($script);

        return $div;
    }

    public function Issues() {
        $user = new Models\User();
        $sess = new Models\Session();
        $edit = new Models\Edition();

        $issues = $user->GetIssues($this->data['user_id']);

        $rows = array();
        for ($i = 0; $i < count($issues); ++$i) {
            $rows[$i] = array($i + 1, $edit->GetItemBrief($issues[$i]['edit_id'], $issues[$i]['item_id']));
            $rows[$i][1]->AddRow('iss_date', new Html\Text('Дата выдачи'),
                    new Html\Text($issues[$i]['iss_date']), true);
            $rows[$i][1]->AddRow('ret_date', new Html\Text('Дата возврата'),
                    new Html\Text($issues[$i]['ret_date']), true);

            $remain = strtotime($issues[$i]['ret_date']) - time();
            $remain = (int)($remain / 86400);
            $veryhot = false;

            if ($remain > 0) {
                $tit = 'Осталось, дней';
            } else {
                $remain = -$remain;
                $tit = 'Просрочена, дни';
                $veryhot = true;
            }
            $rows[$i][1]->AddRow('remain', new Html\Text($tit),
                    new Html\Text($remain), true, $veryhot);
        }

        $table = new Html\QueryTable($rows, array("№", "Описание"));
        $table->id = "ReaderIssueTable";
        $table->SetAttribute('class', $table->Attribute('class').' EditionList');

        $rows = $table->First()->Childs();
        $rows[0]->First()->SetAttribute("class", "ControlCell");
        $rows[0]->AddData()->Added()->SetAttribute("class", "ControlCell");

        for ($i = 1; $i < count($rows); ++$i) {
            $issue_id = $i ? $issues[$i - 1]['issue_id'] : "";
            $edit_id = $i ? $issues[$i - 1]['edit_id'] : "";
            $item_id = $i ? $issues[$i - 1]['item_id'] : "";

            $rows[$i]->id = '';
            $rows[$i]->First()->SetAttribute("style", "text-align: center");
            $rows[$i]->AddData()->Added()->SetAttribute("style", "text-align: center")
                ->Add(new Html\A(array('href' => '?',
                    'data-issue' => $issue_id,
                    'data-edit' => $edit_id,
                    'data-item' => $item_id)))
                ->Added()->Add(new Html\Img(array(
                    'src' => "pub/media/images/tick_16.png",
                    'class' => "NoneBorder",
                    'alt' => 'Возврат')));
        }

        ////////////////// javascript //////////////////////
        $src = Utils::LoadFileToString(dirname(__FILE__)."/Reader/Issue.js");
        $script = new Html\Script($src);
        ////////////////////////////////////////////////////

        $div = new Html\Div();
        $div->add($table);
        $div->Add($script);

        return $div;
    }

    // профиль
    public function ReaderInfo() {
        $users = new Models\User();
        $pofile = $users->UserProfile($this->data['user_id']);

        $table = new Html\Table();
        $table->SetAttribute('class', 'QueryTable');
        $table->AddBody();


        $i = 0;
        foreach ($pofile as $key => $val) {
            $row = $table->First()->AddRow()->Added();
            $row->AddData()->Added()->Add(new Html\Text($key));
            $row->AddData()->Added()->Add(new Html\Text($val));

            ++$i;
            if ($i % 2) $row->SetAttribute('class', 'Odd');
        }


        $img = new Html\Img(array(
            'src' => 'pub/media/images/user_info_64.png',
            'alt' => 'sdfd',
            'style' => 'padding: 0.4em; border: none'
        ));

        $a = new Html\A(array(
            'href' => '?',
            'id' => 'AltReader'
        ));
        $a->Add($img);

        $div = new Html\Table();
        $div->AddBody();
        $div->SetAttribute('class', 'ProfileTable');

        $row = $div->First()->AddRow()->Added();
        $row->AddData()->Added()->Add($a);
        $row->AddData()->Added()->Add($table);

        return $div;
    }

    public function ReaderOrderSwitch() {
        $page_switch = new Html\PageSwitch("ReaderOrders");
        return $page_switch->ToHtml();
    }

    public function ReaderEditionSwitch() {
        $page_switch = new Html\PageSwitch("ReaderEditions");
        return $page_switch->ToHtml();
    }

    public function TypeField() {
        $select = new Html\HtmlContainer("select", array(
            'id' => "SearchField"
        ));
        $types = array(
            'user_id' => "Ид",
            'fullname' => "ФИО",
            'login' => "Логин"
        );
        foreach ($types as $v => $text) {
            $option = new Html\HtmlContainer("option", array('value' => $v));
            $option->Add(new Html\Text($text));
            $select->Add($option);
        }
        return $select;
    }

    public function NewLogin() {
        $user = new Models\User();
        return 'user'.$user->GetCurrentId();
    }

    public function NewPass() {
        return Utils::RandomString(6, '0123456789');
    }
}
